var model       = module.exports;
var SGProto     = require('./SGProto');
var RoomProto   = require('../../API/RoomProto');
var enumeration = require('../../Constant/enumeration');

model.init = function() {
	console.log("SGModel init");
	Global.MessageCallback.addListener('RoomMessagePush', this);
	Global.MessageCallback.addListener('GameMessagePush', this);
};

model.getMyUid = function () {
	return this.myUid;
};

model.setEntryRoomData = function(msg) {
	/* 游戏数据,随时可恢复场景 */
	this.gameInited      = true;
	this.roomUserInfoArr = msg.roomUserInfoArr;
	this.gameRule        = msg.gameRule;
	this.roomID          = msg.roomID;
	this.roomCreatorInfo = msg.roomCreatorInfo;

	this.gameStatus      = msg.gameData.gameStatus;
	this.gameStarted     = msg.gameData.gameStarted;
	this.tick            = msg.gameData.tick;
	this.bankerChairID   = msg.gameData.bankerChairID;
	this.pourScores      = msg.gameData.pourScores;
	this.robBankScales   = msg.gameData.robBankScales;
	this.handCards       = msg.gameData.handCards;
	this.curBureau       = msg.gameData.curBureau;
	this.maxBureau       = msg.gameData.maxBureau;
	this.chairCount      = msg.gameData.chairCount;
	this.showCards       = msg.gameData.showCards;
	this.userTrustArray  = msg.gameData.userTrustArray;
	this.result          = msg.gameData.result;
	this.curScores       = msg.gameData.curScores;
	this.askForExitArr   = null;
	this.myUid           = Global.UserModel.uid;
};

model.getRoomData = function () {
	var msg = {
		gameInited: true,
		roomUserInfoArr: this.roomUserInfoArr,
		gameRule: this.gameRule,
		roomID: this.roomID,
		roomCreatorInfo: this.roomCreatorInfo,
		gameData: {
			gameStatus: this.gameStatus,
			gameStarted: this.gameStarted,
			tick: this.tick,
			bankerChairID: this.bankerChairID,
			pourScores: this.pourScores,
			robBankScales: this.robBankScales,
			handCards: this.handCards,
			curBureau: this.curBureau,
			maxBureau: this.maxBureau,
			chairCount: this.chairCount,
			showCards: this.showCards,
			userTrustArray: this.userTrustArray,
			result: this.result,
			curScores: this.curScores,
			askForExitArr: this.askForExitArr,
			myUid: Global.UserModel.uid,
		},
	};
	return msg;
};

model.getGameInited = function () {
	return this.gameInited;
};

model.setGameInited = function (value) {
	this.gameInited = value;
};

model.getRoomCreatorChairID = function () {
	for (let user of this.roomUserInfoArr) {
		if (user.userInfo.uid == this.roomCreatorInfo.uid) {
			return user.chairID;
		}
	}
	return null;
};

model.getGameType = function () {
	return this.gameRule.gameFrameType;
};

model.getGameStarted = function () {
	return this.gameStarted;
};

model.getRoomID = function() {
	return this.roomID;
};

model.getCurBureau = function() {
	return this.curBureau;
};

model.getMaxBureau = function() {
	return this.maxBureau;
};

model.messageCallbackHandler = function(router, msg) {
	if(router === 'RoomMessagePush') {
		if(msg.type === RoomProto.GET_ROOM_SCENE_INFO_PUSH) {
			this.setEntryRoomData(msg.data);
		}
		else if(msg.type === RoomProto.OTHER_USER_ENTRY_ROOM_PUSH) {
			if(!this.gameInited) { return; }
			this.addUser(msg.data.roomUserInfo);
		}
		else if(msg.type === RoomProto.USER_LEAVE_ROOM_PUSH) {
			if(!this.gameInited) { return; }
			this.delUser(msg.data.roomUserInfo.chairID);
			if(msg.data.roomUserInfo.chairID === this.getMyChairID()) {
				this.onDestroy();
			}
		}
		else if(msg.type === RoomProto.USER_READY_PUSH) {
			if(!this.gameInited) { return; }
			this.userReady(msg.data.chairID);
		}
		else if(msg.type === RoomProto.ROOM_DISMISS_PUSH) {
			if(!this.gameInited) { return; }
			this.askForExitArr = null;
			this.roomDismissReason = msg.data.reason;
			if (msg.data.reason != enumeration.gameRoomDismissReason.BUREAU_FINISHED) {
				this.onDestroy();
			}
		}
		else if(msg.type === RoomProto.ASK_FOR_DISMISS_PUSH) {
			if(!this.gameInited) { return; }
			this.askForExitArr = msg.data.chairIDArr;
			if (msg.data.chairIDArr.indexOf(false) != -1) {
				this.askForExitArr = null;
			}
		}
		else if(msg.type === RoomProto.USER_CHANGE_SEAT_PUSH) {
			if(!this.gameInited) { return; }
			for (let user of this.roomUserInfoArr) {
				if (user.userInfo.uid == msg.data.uid) {
					user.chairID = msg.data.toChairID;
				}
			}
		}
		else if(msg.type === RoomProto.ROOM_USER_INFO_CHANGE_PUSH) {
			if(!this.gameInited) { return; }
			for (let i = 0; i < this.roomUserInfoArr.length; ++i) {
				if (this.roomUserInfoArr[i].userInfo.uid == msg.data.changeInfo.uid) {
					for (let key in msg.data.changeInfo) {
						this.roomUserInfoArr[i].userInfo[key] = msg.data.changeInfo[key];
					}
				}
			}
		}
		else if(msg.type === RoomProto.USER_OFF_LINE_PUSH) {
			if(!this.gameInited) { return; }
			let user = this.getUserByChairID(msg.data.chairID);
			if (user) {
				user.userStatus |= RoomProto.userStatusEnum.OFFLINE;
			}
		}
	}
	else if(router === 'GameMessagePush') {
		if(!this.gameInited) { return; }
		if(msg.type === SGProto.GAME_BUREAU_PUSH) {
			this.curBureau = msg.data.curBureau;
		}
		else if(msg.type === SGProto.GAME_ROB_BANK_PUSH) {
			this.robBank(msg.data.chairID, msg.data.robScale);
		}
		else if(msg.type === SGProto.GAME_POUR_SCORE_PUSH) {
			this.pourScore(msg.data.chairID, msg.data.score);
		}
		else if(msg.type === SGProto.GAME_SHOW_CARDS_PUSH) {
			this.handCards[msg.data.chairID] = msg.data.cards;
			this.showCards[msg.data.chairID] = 1;
		}
		else if(msg.type === SGProto.RESOUT_CARD_PUSH) {
			this.answerResoutCardPush(msg.data.chairID, msg.data.cardArr);
		}
		else if(msg.type === SGProto.GAME_RESULT_PUSH) {
			this.result = msg.data.result.winScores;
			this.curScores = msg.data.result.curScores;
			this.tick = 0;
		}
		else if(msg.type === SGProto.GAME_STATUS_PUSH) {
			this.tick = msg.data.tick;
			this.gameStatus = msg.data.gameStatus;
			this.gameStarted = true;
			if (this.gameStatus == SGProto.gameStatus.NONE) {
				for (let user of this.roomUserInfoArr) {
					user.userStatus &= ~RoomProto.userStatusEnum.READY;
				}
				this.result = null;
				this.handCards = [null, null, null, null, null, null, null, null, null, null];
				this.robBankScales = [null, null, null, null, null, null, null, null, null, null];
				this.pourScores = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0];
				this.showCards = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0];
				let gameType = this.getGameType();
				if (gameType == SGProto.gameType.QIANGZHUANG || gameType == SGProto.gameType.DACHIXIAOZHUANG || gameType == SGProto.gameType.PAIDAZHUANG) {
					this.bankerChairID = null;
				}
			}
		}
		else if(msg.type === SGProto.GAME_BANKER_PUSH) {
			this.bankerChairID = msg.data.bankerChairID;
			this.robBankScales[this.bankerChairID] = msg.data.robScale;
		}
		else if(msg.type === SGProto.GAME_SEND_CARDS_PUSH) {
			this.handCards = msg.data.handCards;
		}
	}
};

model.robBank = function (chairID, scale) {
	this.robBankScales[chairID] = scale;
};

model.pourScore = function(chairID, score) {
	this.pourScores[chairID] = score;
};

model.userReady = function(chairID){
	let user = this.getUserByChairID(chairID);
	if(user) {
		user.userStatus |= RoomProto.userStatusEnum.READY;
		user.userStatus |= RoomProto.userStatusEnum.DISMISS;
	}
};

model.getGameRule = function() {
	return this.gameRule;
};

model.getGameStatus = function() {
	return this.gameStatus;
};

model.getTick = function () {
	return this.tick;
};

model.subTick = function (dt) {
	this.tick -= dt;
};

model.setTick = function (tick) {
	this.tick = tick;
};

model.onDestroy = function() {
	console.log("SGModel onDestroy");
	Global.MessageCallback.removeListener('RoomMessagePush', this);
	Global.MessageCallback.removeListener('GameMessagePush', this);
};

model.getBankerChairID = function () {
	return this.bankerChairID;
};

model.getChairCount = function() {
	/* return this.chairCount; */
	return this.gameRule.maxPlayerCount;
};

model.getMyChairID = function() {
	for (let user of this.roomUserInfoArr) {
		if (user.userInfo.uid == this.myUid) {
			this.myChairID = user.chairID;
		}
	}
	return this.myChairID;
};

model.getUserByChairID = function(chairID) {
	for (let user of this.roomUserInfoArr) {
		if (user.chairID == chairID) {
			return user;
		}
	}
	return null;
};

model.addUser = function(user) {
	for(var i = 0; i < this.roomUserInfoArr.length; ++i) {
		if(this.roomUserInfoArr[i].chairID === user.chairID) {
			this.roomUserInfoArr.splice(i, 1);
		}
	}
	this.roomUserInfoArr.push(user);
};

model.delUser = function(chairID) {
	for (let i = 0; i < this.roomUserInfoArr.length; ++i) {
		if (this.roomUserInfoArr[i].chairID == chairID) {
			this.roomUserInfoArr.splice(i, 1);
			break;
		}
	}
};

model.getRobScaleByChairID = function (chairID) {
	return this.robBankScales[chairID];
};

model.getPourScoreByChairID = function (chairID) {
	return this.pourScores[chairID];
};

model.getHandCardsByChairID = function (chairID) {
	return this.handCards[chairID] || null;
};

model.getCanPourScores = function () {
	let canPourScores = this.gameRule.canPourScores.slice();
	for (let i = 0; i < canPourScores.length; ++i) {
		canPourScores[i] *= this.gameRule.baseScore;
	}
	if (this.isUnionCreate()) {
		let maxScore = this.getMaxCanPourScore();
		while (canPourScores.length > 0 && canPourScores[canPourScores.length-1] > maxScore) {
			canPourScores.pop();
		}
		if (canPourScores.length == 0) {
			canPourScores.push(1);
		}
	}
	return canPourScores;
};

model.getMaxCanPourScore = function () {
	let maxScore;
	if (this.isUnionCreate()) {
		let user = this.getUserByChairID(this.getMyChairID());
		let score = user.userInfo.score;
		let bankerScale = 1;
		let scale = (this.gameRule.scaleType == SGProto.scaleType.LITTLE)? 1:SGProto.cardsType.BAOZI;
		if (this.bankerChairID != null && this.robBankScales[this.bankerChairID] != null) {
			bankerScale = this.robBankScales[this.bankerChairID];
		}
		maxScore = Math.floor(score/scale/bankerScale);
		if (this.gameRule.maxCanPourGold && maxScore > this.gameRule.maxCanPourGold*this.gameRule.baseScore) {
			maxScore = this.gameRule.maxCanPourGold*this.gameRule.baseScore;
		}
	}
	else {
		maxScore = this.gameRule.maxCanPourGold*this.gameRule.baseScore;
	}
	return maxScore || 1;
};

model.getResult = function () {
	return this.result;
};

model.getHandCards = function () {
	return this.handCards;
};

model.getIsPlayingByChairID = function (chairID) {
	let user = this.getUserByChairID(chairID);
	if (user && ((user.userStatus&RoomProto.userStatusEnum.READY) > 0 || (user.userStatus&RoomProto.userStatusEnum.PLAYING) > 0)) {
		return true;
	}
	return false;
};

model.getShowCards = function (chairID) {
	return this.showCards[chairID] == 1;
};

model.getIsBigScale = function () {
	return this.gameRule.scaleType == SGProto.scaleType.BIG;
};

model.getTrustByChairID = function (chairID) {
	return this.userTrustArray[chairID];
};

model.getCurScore = function (chairID) {
	let user = this.getUserByChairID(chairID);
	if (!user) { return 0; }
	if (this.isUnionCreate()) {
		return Math.floor(user.userInfo.score-this.pourScores[chairID]);
	}
	else {
		return Math.floor(user.userInfo.score);
	}  
};

model.getRoomCreator = function () {
	return this.roomCreatorInfo;
};

model.isUnionCreate = function () {
	return (this.roomCreatorInfo && this.roomCreatorInfo.creatorType == Global.Enum.roomCreatorType.UNION_CREATE);
};

model.getRoomDismissReason = function () {
	return this.roomDismissReason;
};

model.isDismissing = function () {
	return !!this.askForExitArr;
};

